import {Divider, Popconfirm, Table, Input, DatePicker, Select, message} from 'antd'
import React, {useState, useEffect} from 'react'
import styles from "@/pages/Info/Edit/style.less";
import {connect} from 'umi'
import moment from 'moment'
import {awardTypeList} from '@/utils/constant'
import {formatNumber} from "@/utils/utils";

const {Option} = Select;

const TableForm = ({userCodeList, onChange,show,delFunction}) => {
  const [clickedCancel, setClickedCancel] = useState(false);
  const [loading, setLoading] = useState(false);
  const [cacheOriginData, setCacheOriginData] = useState({});
  const [data, setData] = useState([]);


  useEffect(() => {
    let newData = [...data];
    userCodeList.forEach((item) => {
      if (!newData.find(item2 => item2.employeeCode === item.employeeCode)){
        newData.push({
          ...item,
          monthOne: item.monthOne && moment(item.monthOne),
          monthTwo: item.monthTwo && moment(item.monthTwo),
          key: item.employeeCode
        })
      }
    });
    setData(newData);
    onChange(newData);
  }, [userCodeList]);

  const getRowByKey = (employeeCode, newData) => (newData || data)?.filter((item) => item.employeeCode === employeeCode)[0];

  const toggleEditable = (e, employeeCode) => {
    e.preventDefault()
    const newData = data?.map((item) => ({...item}));
    const target = getRowByKey(employeeCode, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[employeeCode] = {...target};
        setCacheOriginData(cacheOriginData)
      }
      target.editable = !target.editable;
      setData(newData);
    }
  };

  const remove = (e, employeeCode) => {
    const newData = [...data];
    let datas = newData.filter(item => item.employeeCode != employeeCode);
    setData(datas);
    onChange(datas);
    delFunction(employeeCode)
  };

  const handleFieldChange = (e, fieldName, employeeCode) => {
    const newData = [...data];
    const target = getRowByKey(employeeCode, newData);
    if (target) {
      target[fieldName] = e && e.target ? e.target.value : e;
      if (target[fieldName] && (fieldName === 'monthOne' || fieldName === 'monthTwo')) {
        target[fieldName] = target[fieldName] || '';
        let ctm = moment(target.monthOne).format('YYYY-MM');
        if(parseInt(target.amountTwo) !== 0){
          let etm = target.monthTwo ? moment(target.monthTwo).format('YYYY-MM') : '';
          if (ctm === etm) {
            message.error("兑换月份不能相同！");
            target.monthTwo = '';
            return
          }
          target.monthTwo = moment(target.monthTwo).add(1,'M').date(1);
        }
        target.monthOne = moment(target.monthOne).date(1);
      }
      setData(newData);
    }
  };

  const updateRow = (e, rowKey) => {
    e.persist();
    if (clickedCancel) {
      setClickedCancel(false);
      return
    }
    const newData = [...data];
    const target = getRowByKey(rowKey, newData);
    if(target.awardType !== 0 && target.awardType !== 1){
      message.error("奖罚类型不能为空！");
      return;
    }
    if(!target.amount || target.amount === 0){
      message.error("奖罚金额不能为空！");
      return;
    }
    if(!target.amountOne || target.amountOne === 0){
      message.error("金额1不能为空！");
      return;
    }
    if(!target.monthOne || target.amountOne === ""){
      message.error("兑换月份1不能为空！");
      return;
    }
    toggleEditable(e, rowKey);
    const {isNew, editable, key} = target;
    onChange(data);
  };

  const cancel = (e, employeeCode) => {
    setClickedCancel(true);
    e.preventDefault();
    const newData = [...data]; // 编辑前的原始数据
    let cacheData = [];
    cacheData = newData.map((item) => {
      if (item.employeeCode === employeeCode) {
        if (cacheOriginData[employeeCode]) {
          const originItem = {...item, ...cacheOriginData[employeeCode], editable: false}
          delete cacheOriginData[employeeCode]
          setCacheOriginData(cacheOriginData)
          return originItem
        }
      }
      return item
    });
    setData(cacheData)
    setClickedCancel(false)
  };

  const computeScale = (e, fieldName, employeeCode) => {
    const newData = [...data];
    const target = getRowByKey(employeeCode, newData);
    if (target) {
      target[fieldName] = e.target ? e.target.value : e;
      if(fieldName === 'amount'){
        target.amountOne = 0;
        target.amountTwo = 0;
      }else{
        let sum = target.amount - target.amountOne;
        target.amountTwo = sum;
        target.proportionOne = ((target.amountOne / target.amount) * 100).toFixed(2);
        target.proportionTwo = ((sum / target.amount) * 100).toFixed(2);
      }
      setData(newData);
    }
  };

  const columns = [
    {
      title: '工号',
      dataIndex: 'employeeCode',
      disabled: true,
      fixed: 'left',
      width: 110
    },
    {
      title: '姓名',
      dataIndex: 'employeeName',
      disabled: true,
      fixed: 'left',
      width: 110
    },
    {
      title: '公司',
      dataIndex: 'orgname',
      disabled: true,
      width: 150
    },
    {
      title: '部门',
      dataIndex: 'unitname',
      disabled: true,
      width: 150
    },
    {
      title: '奖罚类型',
      dataIndex: 'awardType',
      key: 'awardType',
      width: 120,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择" value={text}
                    onChange={(e) => handleFieldChange(e, 'awardType', record.employeeCode)}>
              {awardTypeList.map((item, index) => {
                return (
                  <Option value={item.value} key={item.value}>
                    {item.label}
                  </Option>
                )
              })}
            </Select>
          )
        }
        const res = awardTypeList.find((item) => item.value === parseInt(text));
        return res ? res.label : text
      },
    },
    {
      title: '奖罚金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 150,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input value={text} autoFocus onChange={(e) => computeScale(e, 'amount', record.employeeCode)}
                   suffix="元"
            />
          )
        }
        return (text != undefined ? formatNumber(text) : 0) + '元'
      },
    },
    {
      title: '奖罚比例1（%）',
      dataIndex: 'proportionOne',
      key: 'proportionOne',
      disabled: true,
      width: 100,
      render: (text) => {
        return (text != undefined ? formatNumber(text) : 0) + '%'
      },
    },
    {
      title: '金额1',
      dataIndex: 'amountOne',
      key: 'amountOne',
      width: 130,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input
              disabled={!record.amount}
              onChange={(e) => computeScale(e, 'amountOne', record.employeeCode)}
              value={text}
              placeholder="请输入金额" suffix="元"
            />
          )
        }
        return (text != undefined ? formatNumber(text) : 0) + '元'
      },
    },
    {
      title: '兑换月份1',
      dataIndex: 'monthOne',
      key: 'monthOne',
      width: 150,
      render: (text, record) => {
        if (record.editable) {
          return (
            <DatePicker value={text} picker="month" onChange={(e) => handleFieldChange(e, 'monthOne', record.employeeCode)}/>
          )
        }
        return text ? moment(text).format('YYYY-MM') : '';
      },
    },
    {
      title: '奖罚比例2（%）',
      dataIndex: 'proportionTwo',
      key: 'proportionTwo',
      disabled: true,
      width: 100,
      render: (text) => {
        return (text != undefined ? formatNumber(text) : 0) + '%'
      },
    },
    {
      title: '金额2',
      dataIndex: 'amountTwo',
      key: 'amountTwo',
      disabled: true,
      width: 130,
      render: (text) => {
        return (text != undefined ? formatNumber(text) : 0) + '元'
      },
    },
    {
      title: '兑换月份2',
      dataIndex: 'monthTwo',
      key: 'monthTwo',
      width: 150,
      render: (text, record) => {
        if (record.editable) {
          return (
            <DatePicker value={text} picker="month" onChange={(e) => handleFieldChange(e, 'monthTwo', record.employeeCode)}/>
          )
        }
        return text ? moment(text).format('YYYY-MM') : '';
      },
    },
  ];

  if(!show){
    columns.push({
      title: '操作',
      key: 'action',
      width: 110,
      fixed: 'right',
      render: (text, record) => {
        if (!!record.editable && loading) {
          return null
        }
        if (record.editable) {
          return (
            <span>
              <a onClick={(e) => updateRow(e, record.employeeCode)}>保存</a>
              <Divider type="vertical"/>
              <a onClick={(e) => cancel(e, record.employeeCode)}>取消</a>
            </span>
          )
        }
        return (
          <span>
            <a onClick={(e) => toggleEditable(e, record.employeeCode)}>编辑</a>
            <Divider type="vertical"/>
            <Popconfirm title="是否要删除此行？" cancelText='取消' okText='确认' onConfirm={(e) => remove(e, record.employeeCode)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        )
      },
    },)
  }
  return (
    <>
      <Table
        loading={loading}
        columns={columns}
        dataSource={data}
        rowKey="key"
        pagination={false}
        rowClassName={(record) => (record.editable ? styles.editable : '')}
        scroll={{x: 1300}}
      />
    </>
  )
}

export default connect(({recruitment}) => ({
  recruitment,
}))(TableForm)

